<?php

    function _tvn_common_address_book_update($aid, $data) {
        return db_update('tvn_users_address_book')->fields($data)->condition('aid', $aid)->execute();
    }

    function _tvn_common_user_num_address_book($uid) {
        $query = db_select('tvn_users_address_book', 'a');
        $query->addExpression('COUNT(a.aid)', 'count');
        $query->condition('a.uid', $uid);
        return $query->execute()->fetchField();
    }

    function _tvn_common_insert_data($table, $data) {
        return db_insert($table)->fields($data)->execute();
    }

    function _tvn_common_find_shelf_for_item() {
        $sid = 0;
        $num_shelf = variable_get('item_per_shelf', 0);
        $shelfs = _tvn_common_get_all_shelf();
        foreach ($shelfs as $shelf) {
            $count = _tvn_common_count_item_in_shelf($shelf->tid);
            if ($count < $num_shelf) {
                $sid = $shelf->tid;
                break;
            }
        }
        return $sid;
    }

    function _tvn_common_get_all_shelf() {
        $list = array();
        $terms = taxonomy_get_tree(5);
        foreach ($terms as $term) {
            if ($term->depth == 2) {
                $list[$term->tid] = $term;
            }
        }
        return $list;
    }

    function _tvn_common_count_item_in_shelf($tid) {
        $query = db_select('node', 'n');
        $query->leftJoin('field_data_field_incom_tracking', 'ic', 'n.vid = ic.revision_id');
        $query->addExpression('COUNT(n.nid)', 'count');
        $query->condition('n.status', 1);
        $query->condition('n.type', 'warehouse_package');
        $query->condition('ic.field_incom_tracking_value', $tid);
        return $query->execute()->fetchField();
    }

    function tvn_common_get_related_nids($nid) {
        $query = db_select('node', 'n');
        $query->leftJoin('field_data_field_item_package', 'p', 'n.vid = p.revision_id');
        $query->fields('n', array('nid'));
        $query->condition('n.status', 1);
        $query->condition('n.type', 'warehouse_items');
        $query->condition('p.field_item_package_nid', $nid);
        return $query->execute()->fetchCol();
    }

    function tvn_common_get_packages_user($uid) {
        $query = db_select('node', 'n');
        $query->leftJoin('field_data_field_author_uid', 'a', 'n.vid = a.revision_id');
        $query->fields('n', array('nid'));
        $query->condition('n.status', 1);
        $query->condition('n.type', 'warehouse_package');
        $query->condition('a.field_author_uid_value', $uid);
        return $query->execute()->fetchCol();
    }

    function tvn_common_get_order_user($uid, $oids = array()) {
        $query = db_select('tvn_order', 'o');
        $query->fields('o');
        $query->condition('o.uid', $uid);
        $query->condition('o.status', 2);
        if (!empty($oids)) {
            $query->condition('o.oid', $oids);
        }
        return $query->execute();
    }
